<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>防抖案例</title>
</head>
<body>
    <input type="text" class="inp">

<script>

    var oInp = document.getElementsByClassName("inp")[0];
    oInp.onkeyup = throttle(changeInp,1000);
    function changeInp(){
        console.log(1);
    }

    function throttle(fn,time){
        var t = null,
            begin = new Date().getTime(),  //开始时间
            res;

        var throttled = function(){
            var _this = this,
                nowDate = new Date().getTime(); //不断更新时间

            if(t){   //每次执行，判断是否有定时器，有则清除
                clearTimeout(t);
            }
            if(nowDate - begin >= time){    // 用户持续执行 大于 设置时间，当：当前时间 - 开始时间 > 设置的时长
                // 则会执行一次这里的代码
                res = fn.apply(_this);
                begin = nowDate;   //开始时间重置
            }else{
                //说明用户停止行为，我们需要最后在执行一次
                t = setTimeout(function(){
                    res = fn.apply(_this);
                },time);
            }
            return res;
        };
        throttled.remove = function(){
            clearTimeout(t);
            t = null;
        };
        return throttled;
    }
</script>
</body>
</html>
